package com.venutech.gongan.api;

import com.baomidou.mybatisplus.plugins.Page;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import com.venutech.gongan.common.Constants;
import com.venutech.gongan.entity.Jkxt;
import com.venutech.gongan.entity.*;
import com.venutech.gongan.model.ResultFormat;
import com.venutech.gongan.service.*;
import com.venutech.gongan.util.ResultUtil;
import com.venutech.gongan.vo.Operation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

//import com.venutech.gongan.service.oauth.OAuthTokenContext;

//import com.shihang.misc.date.DateTimeUtil;
//import com.venutech.imd.common.Constants;
//import com.venutech.imd.entity.*;
//import com.venutech.imd.model.ResultFormat;
//import com.venutech.imd.service.*;
//import com.venutech.imd.service.authentication.oauth.OAuthTokenContext;
//import com.venutech.imd.util.ResultUtil;
//import com.venutech.imd.util.StringUtils;

@Api(value = "前端摄像机控制层接口", tags = "前端摄像机控制层接口")
@RestController
public class QdsxjController extends AbstractControllerBase {

    @Resource
    private WorkService workService;
    @Resource
    private QdsxjService qdsxjService;
    @Resource
    private RzLogService rzLogService;
    @Resource
    private JkxtService jkxtService;
    @Resource
    private DictDataService dictDataService;
    @Autowired
    private ISysUserService sysUserService;
//    @Autowired
//    @Qualifier("eventThreadPool")
//    ExecutorService eventThreadPool;
//    @Autowired
//    private OAuthTokenContext oauthContext;

    Logger logger = LoggerFactory.getLogger(QdsxjController.class);

    @ApiOperation("摄像头列表查询")
    @GetMapping("/qdsxj_List")
    public Map<String, Object> qdsxj_List(@RequestParam Integer page, @RequestParam Integer limit,
                                          @RequestParam(required = false) String begintime,
                                          @RequestParam(required = false) String endtime,
                                          @RequestParam(required = false) String badw,
                                          @RequestParam(required = false) String sb_type,
                                          @RequestParam(required = false) String sb_state,
                                          @RequestParam(required = false) String sb_name,
                                          @RequestParam(required = false,defaultValue = "0") Integer type) {
        Map<String, Object> result = new HashMap<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //User currentUser = oauthContext.getCurrentUser();
        SysUser currentUser = sysUserService.selectUserById(loginUser.getUserId());
        RzLog rzLog = new RzLog();
        logger.info( "传递参数: sb_type={}============="+sb_type+"sb_state={}============"+sb_state);
        Page<Qdsxj> p = qdsxjService.getInfo(page,limit,begintime,endtime,badw,sb_name,sb_type,sb_state, currentUser);
        result.put("code","0");
        result.put("count",p.getTotal());
        result.put("data",p.getRecords());
        if(type==1){
            if(p.getTotal()>0){
                String message =null;
                if(StringUtils.isEmpty(sb_name)){
                    message = String.format("前端摄像机查询：点位名称=%s",sb_name);
                }
                if(StringUtils.isEmpty(sb_type)){
                    message = String.format("前端摄像机查询：点位名称=%s",sb_type);
                }
                if(StringUtils.isEmpty(sb_state)){
                    message = String.format("前端摄像机查询：点位名称=%s",sb_state);
                }
                String opCondition = String.format("message=%s",message);
                asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_QUERY, Constants.QUERY, opCondition, message);
                result.put("msg","前端摄像机查询成功");
            }else{
                String message =String.format("前端摄像机查询：点位名称:%s,设备类型:%s,设备状态:%s",sb_name,sb_type,sb_state);
                String opCondition = String.format("sb_name=%s and sb_type=%s", sb_name, sb_type);

                asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_QUERY, Constants.QUERY, opCondition, message);
                result.put("msg","前端摄像机查询失败");
            }
        }else{
            result.put("msg","前端摄像机查询成功");
        }
        return result;
    }
    @ApiOperation("前端摄像机新增")
    @PostMapping("/qdsxjSave")
    public ResultFormat qdsxjSave(Qdsxj qdsxj){
        Log log=new Log();
        log.setCzlx(Constants.INSERT);
        ResultFormat insert = qdsxjService.insert(qdsxj);
        if (insert.getCode() == 200) {
            String message =String.format("前端摄像机保存：摄像机编号:%d,摄像机名称:%s",qdsxj.getSb_bm(),qdsxj.getSb_name());
            String opCondition = String.format("摄像机编号=%s and 摄像机名称=%s", qdsxj.getSb_bm(),qdsxj.getSb_name());
            asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_QUERY, Constants.QUERY, opCondition, message);

            return ResultUtil.success();
        }


        String message =String.format("前端摄像机保存：摄像机编号:%d,摄像机名称:%s",qdsxj.getSb_bm(),qdsxj.getSb_name());
        String opCondition = String.format("摄像机编号=%s and 摄像机名称=%s", qdsxj.getSb_bm(),qdsxj.getSb_name());

        asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_QUERY, Constants.QUERY, opCondition, message);

        return ResultUtil.error(100, "添加失败");

    }
    @ApiOperation("前端摄像机删除")
    @GetMapping("/qdsxjDelete")
    public Integer qdsxjDelete(@RequestParam String sb_id) {
        Log log=new Log();
        log.setCzlx(Constants.DELETE);
        int i = qdsxjService.deleteById(Integer.parseInt(sb_id));
        Qdsxj qdsxj = qdsxjService.getById(Integer.parseInt(sb_id));

        if (i > 0) {

            String message =String.format("摄像机删除：摄像机Id:%d,摄像机名称:%s",qdsxj.getSb_id(),qdsxj.getSb_name());
            String opCondition = String.format("摄像机Id=%d and 摄像机名称=%s", qdsxj.getSb_bm(),qdsxj.getSb_name());
            asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_DELETE, Constants.DELETE, opCondition, message);
            //正常
            return 0;
        } else {
            String message = String.format("摄像机删除：摄像机Id:%d,摄像机名称:%s", qdsxj.getSb_id(), qdsxj.getSb_name());
            String opCondition = String.format("摄像机Id=%d and 摄像机名称=%s", qdsxj.getSb_bm(), qdsxj.getSb_name());
            asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_DELETE, Constants.DELETE, opCondition, message);
            //异常
            return -1;
        }
    }

    //修改跳转
    @ApiOperation("修改的下拉选项框")
    @PostMapping("/options")
    public Map<String, Object> qdsxjUpdateView(){
        Map<String, Object> model = new HashMap<>();
        //查询监控系统
        List<Jkxt> jkxtList = jkxtService.getSelectAll();
        //获取联网属性
        List<DictData> lwsxList = dictDataService.getSellwsx();
        //获取设备状态
        List<DictData> sbztList =dictDataService.getSelsbzt();
        //设备厂商
        List<DictData> sbcsList =dictDataService.getSelsbcs();
        //行政区域 姑苏区
        List<DictData> zxbmList =dictDataService.getSelzxbm();
        //摄像机类型
        List<DictData> sxjlxList =dictDataService.getSelsxjlx();
        //摄像机功能类型
        List<DictData> sxjgnlxList =dictDataService.getSelsxjgnlx();
        //位置类型
        List<DictData> sxjwzlxList =dictDataService.getSelsxjwzlx();
        //摄像机补光属性
        List<DictData> sxjbgsxList =dictDataService.getSelsxjbgsx();
        //监视方位
        List<DictData> jsfwList =dictDataService.getSeljsfw();
        //最高分辨率
        List<DictData> zcfblList =dictDataService.getSelzcfbl();
        //摄像机编码格式
        List<DictData> sxjbmgsList =dictDataService.getSelsxjbmgs();
        //公安机关 苏州市
        List<DictData> gajgList =dictDataService.getSelgajg();
        //所属部门
        List<DictData> ssbmhyList =dictDataService.getSelssbmhy();
        //所属部门
        List<DictData> sbsslxList =dictDataService.getSelsbsslx();
        if(sbsslxList.isEmpty() && ssbmhyList.isEmpty() && gajgList.isEmpty() && sxjbmgsList.isEmpty() && zcfblList.isEmpty()
        || jsfwList.isEmpty() && sxjbgsxList.isEmpty() && sxjwzlxList.isEmpty() && sxjgnlxList.isEmpty() && sxjlxList.isEmpty() ||
                zxbmList.isEmpty() && sbcsList.isEmpty() && sbztList.isEmpty() && lwsxList.isEmpty() && jkxtList.isEmpty()){
            return model;
        }
        model.put("jkxtList",jkxtList);
        model.put("lwsxList",lwsxList);
        model.put("sbztList",sbztList);
        model.put("sbcsList",sbcsList);
        model.put("zxbmList",zxbmList);
        model.put("sxjlxList",sxjlxList);
        model.put("sxjgnlxList",sxjgnlxList);
        model.put("sxjwzlxList",sxjwzlxList);
        model.put("sxjbgsxList",sxjbgsxList);
        model.put("jsfwList",jsfwList);
        model.put("zcfblList",zcfblList);
        model.put("sxjbmgsList",sxjbmgsList);
        model.put("gajgList",gajgList);
        model.put("ssbmhyList",ssbmhyList);
        model.put("sbsslxList",sbsslxList);

        return model;
    }

    //修改页面添加
    @ApiOperation("前端摄像机修改")
    @PostMapping("/qdsxjUpdate")
    public void qdsxjUpdate(Qdsxj qdsxj){
        qdsxjService.updateQdsxj(qdsxj);

        String message = String.format("更新前端摄像机：　摄像机Id=%d,　摄像机名称=%s", qdsxj.getSb_id(), qdsxj.getSb_name());
        String opCondition = String.format("sb_id=%d", qdsxj.getSb_id());
        asyncSaveLog(Constants.AUDIT_LOG_OP_TYPE_UPDATE, Constants.UPDATE, opCondition, message);
    }

    /**
     * @Description 注释 //DOTO 查看服务器里面所有视频路径及视频名称
     * @Author liuzhengli
     * @Param @param
     * @Create 2021/10/12 16:30
     * @Return JSONObject
     **/
    @ApiOperation("查看服务器里面所有视频路径及视频名称")
    @PostMapping("/vidoList")
    public Map<String,Object> getVidoList(@RequestParam Integer page, @RequestParam Integer limit){
        File file =new File("/qmtg/images/sdk");
        Map<String,Object> result =new HashMap<>();
        List<String> list_Vido = examineVidoFileList(file,new ArrayList<>());
        logger.info("getVidoList:list_Vido={}",list_Vido);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(!list_Vido.isEmpty()){
            for(int i=0;i<list_Vido.size();i++){
                Operation v=new Operation();
                logger.info("getVidoList:list_Vido.get(i).endsWith('.dat')={},list_Vido.get(i).endsWith('.bak')={}",list_Vido.get(i).endsWith(".dat"),list_Vido.get(i).endsWith(".bak"));
                //if(!list_Vido.get(i).substring(list_Vido.get(i).lastIndexOf(".")).equals(".bak") && !list_Vido.get(i).substring(list_Vido.get(i).lastIndexOf(".")).equals(".dat")){
                String fileName=list_Vido.get(i).substring(list_Vido.get(i).lastIndexOf("/")+1);//视频名称
                String filePath = list_Vido.get(i).substring(0,list_Vido.get(i).lastIndexOf("/"));
                String startTime=sdf.format(new Date().getTime());//下载时间
                v.setWork_device_name(fileName);
                v.setWork_device_path(filePath);
                v.setWork_device_date(startTime);
                v.setWork_device_type(0);
                if(Objects.isNull(workService.getOperationById(v))){
                    workService.insertOperation(v);
                }
                //}
            }
        }

        int work_device_type=0;//视频
        Page<Operation> list = workService.selectOperationList(page,limit,work_device_type);
        logger.info("getVidoList:list={}",list);
        result.put("code","0");
        result.put("msg","成功");
        result.put("count",list.getTotal());
        result.put("data",list.getRecords());
        return  result;
    }

    private  List<String> examineVidoFileList(File file, List<String> list){
        logger.info("examineVidoFileList:file={}",file);
        String filePaht=null;
        boolean bool=false;
        if(file.isDirectory()){
            for(File f:file.listFiles()){
                examineVidoFileList(f,list);
            }
        }else{
            filePaht=file.getAbsolutePath();
            if(StringUtils.isNotEmpty(filePaht)){
                bool=true;
            }
        }
        if(bool){
            list.add(filePaht);
        }
        logger.info("examineVidoFileList:list()={}",list);
        return list;
    }

}
